import store from '../store/index';
export default {
	/**
	 * 接口名称 lo
	 * apiName（obj）
	 */
	apiName: {
		upload_images: 'upload/images', 		// 上传图片
	},
	
	/**
	 * 封装请求（async await 封装uni.request）
	 * method	   post/get		
	 * endpoint    接口方法名
	 * data		   所需传递参数	
	 * load		   是否需要loading
	 */
	async apiUploadCall(method, endpoint,fileArray, data) {
		
		
		// let fullurl = 'http://127.0.0.1:8000/api/' + endpoint;
		let fullurl = 'https://www.cqjbgyq.cn/api/' + endpoint;
		// let Authorization = `${store.state.userInfo.tokenHead}${store.state.userInfo.token}`;
		// let Authorization = `Bearer ${store.state.userInfo.token}`;
		let uu = uni.getStorageSync('userInfo');
		let Authorization = `Bearer ${uu.token}`;//防止浏览器直接手动清除storage后调用接口，手动清除storage后不刷新页面store中存储的值还在，所以改用直接获取storage的方式
		return this.uploadFiles(fileArray,Authorization,fullurl);		
	},
	
	//上传图片
	async uploadFiles(images,Authorization,fullUrl){
		
		uni.showLoading({
			title: '请稍后..',
			mask: true,
		})
		let uploadUrl;
		try{
			uploadUrl = await this.uploadImage(images[0],Authorization,fullUrl);
			
		}catch(err){
			uni.hideLoading();
			uni.showToast({
				title: err,
				icon: 'none',
				mask:true
			});
			return;
		}
	
		if(uploadUrl !== false){
			images.splice(0, 1);	
			//判断是否需要继续上传
			if(images.length > 0){
				this.uploadFiles(images);
			}else{
				uni.hideLoading();
			}
		}else{
			//上传失败处理
			uni.hideLoading();
			uni.showToast({
				title: '上传中出现问题，已终止上传',
				icon: 'none',
				mask: true,
				duration: 2000
			});
		}
		return uploadUrl;
	},
	
	uploadImage: function(file,Authorization,fullUrl){
		return new Promise((resolve, reject)=> {
			//发送给后端的附加参数
			const formData = {
				thumb_mode: 1,  
			};
			uni.uploadFile({
				url: fullUrl, 
				filePath: file,
				name: 'file',
				formData: formData,
				header: {
					// 'Content-Type': 'application/x-www-form-urlencoded',
					// 'content-type': 'application/json',
					'Authorization':  Authorization || ''
				},
				success(uploadFileResult){
					const uploadFileRes = JSON.parse(uploadFileResult.data) || {};
					
					if(uploadFileRes.code === 0 && uploadFileRes.data){
						resolve(uploadFileRes.data);
					}else{
					
						reject(uploadFileRes.msg);
					}
				}, 
				fail(error){
					console.log(error,123)
					reject('网络链接错误');
				}
			});
			
		});
	}
}
